Page({
  data: {
    resources: [{
        id: 'seed',
        img: '/static/seed.png',
        price: 2000
      },
      {
        id: 'fertilizer',
        img: '/static/fertilizer.png',
        price: 1000
      },
      {
        id: 'water',
        img: '/static/water.png',
        price: 500
      },
    ],
    commodity: [],
    showOverlay: false,
    showTreasureBox: false,
    showbox: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.showTreasureBoxWithRandomPosition();
    const resources = this.data.resources;
    // 过滤出你想要显示的商品
    const filteredResources = resources.filter(item => ['seed', 'fertilizer', 'water'].includes(item.id));
    this.setData({
      filteredResources
    });
  },

  /**
   * 显示随机位置的宝箱
   */
  showTreasureBoxWithRandomPosition: function () {
    // 20%的概率显示宝箱
    const shouldShow = Math.random() < 0.2;
    if (shouldShow) {
      this.setData({
        showTreasureBox: true,
      });
    }
  },

  /**
   * 展示购买弹窗遮罩
   * @param {object} e - 事件对象，包含当前点击元素的数据集合
   */
  showOverlay: function (e) {
    const resourceId = e.currentTarget.dataset.resourceId;
    // 根据资源ID，在资源数组中找到对应的资源ID
    const resource = this.data.filteredResources.find(item => item.id === resourceId);
    this.setData({
      selectedResource: resource,
      selectedResourceId: resourceId,
      showOverlay: true
    });
  },

  /**
   * 隐藏购买弹窗遮罩
   */
  hideOverlay: function () {
    this.setData({
      showOverlay: false,
      showbox: false
    });
  },

  /**
   * 点击宝箱的事件处理函数
   */
  onTapTreasureBox() {
    this.setData({
      showbox: true
    });
  },

  /**
   * 确认购买
   * 从资源列表中获取选定资源的价格，然后调用子组件进行购买操作
   */
  confirmPurchase: function () {
    const resourceId = this.data.selectedResourceId;
    let price = 0;
    // 在资源数组中查找对应价格
    const selectedResource = this.data.resources.find(resource => resource.id === resourceId);
    if (selectedResource) {
      price = selectedResource.price;
    } else {
      console.error('在数组中未找到选定的资源');
      return;
    }
    // 获取子组件实例
    const hssComponent = this.selectComponent('#hss');
    if (hssComponent) {
      hssComponent.purchaseResource(resourceId, price);
    } else {
      console.error('无法找到hss组件实例');
    }
    this.hideOverlay();
  },

  /**
   * 购买宝箱中的种子
   * 直接调用子组件购买优惠种子，种子的价格为600
   */
  shoubox_buy() {
    const hssComponent = this.selectComponent('#hss');
    if (hssComponent) {
      hssComponent.purchaseResource('seed', 600);
    } else {
      console.error('无法找到hss组件实例');
    }
    this.hideOverlay();
  }
})